﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Text;

namespace KL.UFrame.Core.Log
{
    public class CommonLogger:ICommonLogger
    {
        private NLog.ILogger _logger;
        
        public CommonLogger(NLog.Logger logger)
        {
            this._logger = logger;
        }

        public void Error(string message, System.Exception ex = null)
        {
            if (ex != null)
            {
                var exceptionMessage = ex.Message;

                var baseExcetion = ex.GetBaseException() as DbEntityValidationException;
                if (baseExcetion != null)
                {
                    //EF操作数据库异常
                    exceptionMessage += GetAllErrors(baseExcetion);
                }
                else
                {
                    //其它异常
                    var innerException = ex.InnerException;
                    while (innerException != null)
                    {
                        exceptionMessage += Environment.NewLine + innerException.Message;
                        innerException = innerException.InnerException;
                    }
                }
                message += Environment.NewLine + exceptionMessage;

                _logger.Error(message + Environment.NewLine + ex.StackTrace);
            }
            else
            {
                _logger.Error(message);
            }
        }

        public void Info(string message)
        {
            _logger.Info(message);
        }

        public void Debug(string message)
        {
           _logger.Debug(message);
        }

        public static string GetAllErrors(DbEntityValidationException exception)
        {
            StringBuilder errors = new StringBuilder();
            IEnumerable<DbEntityValidationResult> validationResult = exception.EntityValidationErrors;
            foreach (DbEntityValidationResult result in validationResult)
            {
                ICollection<DbValidationError> validationError = result.ValidationErrors;
                foreach (DbValidationError err in validationError)
                {
                    errors.Append(err.PropertyName + ":" + err.ErrorMessage + "\r\n");
                }
            }
            return errors.ToString();
        }
    }
}